package com.xzy.demo.juc.locks;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareData {
    private char sign = 'A';
    Lock lock = new ReentrantLock();
    Condition conditionA = lock.newCondition();
    Condition conditionB = lock.newCondition();
    Condition conditionC = lock.newCondition();

    public void printA() {
        lock.lock();
        try {
            // 判断
            while (sign != 'A') {
                conditionA.await();
            }
            // 干活
            for (int i = 0; i < 2; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            // 通知
            sign = 'B';
            conditionB.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            // 判断
            while (sign != 'B') {
                conditionB.await();
            }
            // 干活
            for (int i = 0; i < 4; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            // 通知
            sign = 'C';
            conditionC.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            // 判断
            while (sign != 'C') {
                conditionC.await();
            }
            // 干活
            for (int i = 0; i < 6; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            // 通知
            sign = 'A';
            conditionA.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

/**
 * @author xzy
 * @date 2021/3/23 20:36
 * 说明：实现多个线程的按序调用，A->B->C三个线程启动：
 * -    AA打印2次，BB打印4次，CC打印6次
 * -    AA打印2次，BB打印4次，CC打印6次
 * -   （重复10轮）
 */
public class ConditionDemo {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareData.printA();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareData.printB();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareData.printC();
            }
        }, "C").start();
    }
}
